package com.liantong.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertyLoader {
	
	public static  PropertyLoader propertyLoader = null;
	
	public static Map<String,Object> propertyMap = new HashMap<String,Object>(); 
	public static Map<String,Long> fileLastModifyTime = new HashMap<String,Long>(); 
	
	Properties  prop = null;
	
	private PropertyLoader(){		
	}
	
	public static PropertyLoader getInstance(){
		if(propertyLoader == null){
			propertyLoader = new PropertyLoader();			
		}
		return propertyLoader;
	}
			
	private Properties loadPropFile(String url) throws IOException {
	    prop = new Properties();
	    prop.load(ClassLoader.getSystemResourceAsStream(url));
	    return prop;
	}	
	
	private Properties loadPropFile(InputStream stream) throws IOException {
		prop = new Properties();
		prop.load(stream);
		return prop;
	}	
	
	
	private void populateProperties(String url) throws IOException{
		prop = loadPropFile(url);
		Enumeration<Object> keys = prop.keys();
		for (; keys.hasMoreElements();){
			String key = (String) keys.nextElement();			
			propertyMap.put(key, prop.get(key));
		}		
	}
	
	private void populateProperties(InputStream stream) throws IOException{
		prop = loadPropFile(stream);
		Enumeration<Object> keys = prop.keys();
		for (; keys.hasMoreElements();){
			String key = (String) keys.nextElement();			
			propertyMap.put(key, prop.get(key));
		}		
	}
	
	public  Object getValue(String fileUrl,String key) throws Exception {
		URL url = Thread.currentThread().getContextClassLoader().getResource(fileUrl);
		File file = new File(url.toURI());
		long lastModify = file.getAbsoluteFile().lastModified(); 	
		
		if(fileLastModifyTime.containsKey(fileUrl)){
			//文件有更新，重新加载属性值
			if(lastModify>fileLastModifyTime.get(fileUrl)){				
				InputStream in = new FileInputStream(file);			
				populateProperties(in);
				fileLastModifyTime.put(fileUrl,lastModify);		
			}
		}else{
			InputStream in = new FileInputStream(file);			
			populateProperties(in);
			fileLastModifyTime.put(fileUrl,lastModify);			
		}		
		return prop.get(key);		
	}

}
